//
//  UITextView+Emoticon.swift
//  01-表情键盘(绑定数据)
//
//  Created by gxiangzi on 15/9/14.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

extension UITextView {

    var emoticon:String {
        
        let attrText = attributedText
        
        // 创建一个可变字符串
        var strM = String()
        
        // OC * stop = yes
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
          
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                print("表情图片 \(attachment.chs)")
                strM += attachment.chs!
            } else {
                let str = (attrText.string as NSString).substringWithRange(range)
                print("文本内容：\(str)")
                 strM += str
            }
        }
        return strM
    }
    

    // 插入表情符号
func insertEmoticon(emoticon:Emoticon) {
    
    // 0.空白表情
    if emoticon.isBlack {
        return
    } else if emoticon.emoji != nil {
        // 1.emoji
        replaceRange(selectedTextRange!, withText: emoticon.emoji!)
        return
    } else if emoticon.isRemove
    {
        // 2.删除按钮
        deleteBackward()
        return
    } else {
        
        let imageText = EmoticonAttachment.emoticonAttributeText(emoticon,font: font!)
        
        // 1.从textView中取出属性文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        // 2.插入图片文字
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        // 3.重新设置textView的数值
        // 1> 记录当前光标位置
        let range = selectedRange
        // 2> 设置内容
        attributedText = strM
        // 3> 恢复光标位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
    }
    
}

}
